﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using AgencyEntityLib.BaseEntity;
using Ecopsy.DataTier;
using FormControllers;
using System.Reflection;
using Ecopsy.Tools;

public partial class iSales_Contract : iSales_Page
{
    // SetAlertForTextBox
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        
        SetAlertForTextBox(this.Controls, "TextBox", "onChange", "ShowAlert()");
        SetMsg_EditStatus();        
    }
  
    protected void Page_Load(object sender, EventArgs e)
    {
        

        if (!IsPostBack)
        {
            InitControls();
            MyDataBind();         
            
        }
        InitControls();
    }

    // инициализировать контролы редактирования клиента и списка порхностей/периодов
    private void InitControls()
    {   
        ctlSideShedule1.Contract = this.Contract;
        ctlPaymentsPlan1.ContractSupplier   = ctlSurfaceListBrowser_ContracttSupplier;
        //Инициализация SideShedule
        if (MultiView1.ActiveViewIndex == 0)            
        {
            ctlSurfaceListBrowser1.ContractSupplier = ctlSurfaceListBrowser_ContracttSupplier;
            ctlSurfaceListBrowser1.OnCancel = ctlSurfaceListBrowser_OnCancel;
            ctlSurfaceListBrowser1.OnSave = ctlSurfaceListBrowser_OnSave;
        }


        if (null != lvClient.EditItem)
        {
            Ctl_ctlClientListSelector c = (Ctl_ctlClientListSelector)lvClient.EditItem.FindControl("ctlClientListSelector1");
            c.OnSelectedChange          = ctlClietEditorl_OnSelectedClick;
            c.OnCancel                  = ctlClietEditorl_OnCancelClick;
        }
        
        ctlPaymentsPlan1.OnSave             = ctlSurfaceListBrowser_OnSave;
        //ctlPaymentsPlan1.OnRefresh        = ctlPaymentsPlan1_OnRefresh;
            
        }
        
        

    

    //событие  Cancel контрола ClietEditor
    private bool ctlClietEditorl_OnCancelClick()
    {
        lvClient.EditIndex = -1;
        lvClient.DataSource = ContractAsList;
        lvClient.DataBind();
        return true;
    }

    //событие Cancel контрола SurfaceListBrowser
    private bool ctlSurfaceListBrowser_OnCancel()
    {
        
        return true;

    }

    

    /// <summary>
    /// событие сохранить изменения от контрола SurfaceListBrowser
    /// </summary>
    /// <returns></returns>
    private bool ctlSurfaceListBrowser_OnSave()
    {
        if (!ContractSave())
                    return false;

        pnlSumma.DataBind();
        updSumma.Update();
        updSaveStatus.Update();
        return true;
    }

    //Проверить и сохранить контракт 
    private bool ContractSave()
    {
        bool bOk = Check();

        if (!bOk)
            return bOk;

        SaveContract();
        return bOk;

    }

    //Сохранить контракт если новый сделать редирект страницы
    private void SaveContract()
    {
        wsContract ws = (wsContract)GlobalConstants.CurrentAgency.WS_FactoryList[WS_FactoryList.wsKey_Contract]; 
        Contract c = ws.SaveContract(Contract);

        if (IsNewRecord(ContractID))
        {
            bool isEnabled = true;
            string sUrlKey = GlobalConstants.SiteMapItem_iSales_Contract;
            iPageController.SetPageUrl(ref sUrlKey, ref isEnabled);
            string s = "PageProcessor.aspx?Page=" + sUrlKey + ".aspx?" + iSales_Page.qContractID + "=" + c.ID;
            Response.Redirect(s);
        }        
        updSaveStatus.Update();
    }

    // Видимость метки Есть несохраненные данные    
    protected string GetStateVisible()
    {
        if (Contract.State != EntityState.Loaded) return string.Empty;        
        return "hidden";

    }
    
    //видимость блока финансов
    protected bool VisibleFinance 
    {
        get 
        {
            if (Contract.ContractStatus is ContractStatus_Advice)
                return false;
            if (Contract.ContractStatus is ContractStatus_Reserv)
                return false;

            return true; 
        }
    }

    // Обновление метки Есть несохраненные данные    
    protected void SetMsg_EditStatus()
    {
        lblClientStatus.DataBind();
        updSaveStatus.Update();
    }
    
    private bool ctlContractSurfaceList1_OnEditClick()
    {        
        //mvSidelist.ActiveViewIndex = 1;
        //ctlContractSurfaceListEdit1.DataBind(); 
        return true; 
    }
    
    protected  ContractSurfaceItemList ctlContractSurfaceList1_GetSurfaceItemList()
    {
        ///Contract.SurfaceList.Reset();
        return new ContractSurfaceItemList();
        //return Contract.SurfaceList;
    }

    private void MyDataBind()
    {        
        lvClient.DataSource = ContractAsList;
        //lvMode.DataSource = ContractAsList;
        lvContractStatus.DataSource = ContractAsList;

        if (MultiView1.ActiveViewIndex == 0)
        {
            ctlSurfaceListBrowser1.ContractSupplier = ctlSurfaceListBrowser_ContracttSupplier;
        }

              
        if (Contract.ContractStatus is ContractStatus_Reserv )
                lvContractStatus.EditIndex = 0;
        else
            lvContractStatus.EditIndex = -1;

        InitControls();
        DataBind ();

        //if (lvMode.EditIndex == -1)+
        //{
        //    Ctl_ctlSurfaceListBrowser c = (Ctl_ctlSurfaceListBrowser)lvMode.Items[0].FindControl("ctlSurfaceListBrowser1");
        //    c.ContractSupplier = ctlSurfaceListBrowser_ContracttSupplier;
        //    c.ContractSupplier = ctlSurfaceListBrowser_ContracttSupplier;
        //    c.DataBind();
        //}
    }

    private void ReadForm()
    {

        Contract.Number = txt_number.Text;
        Contract.SignDate = Convert.ToDateTime(txt_dtSignDate.Text);

        // Редактирование статуса?
        if (lvContractStatus.EditIndex > -1)
        {
            TextBox t = (TextBox)lvContractStatus.EditItem.FindControl("txtReservdDate");
            Contract.ContractStatus = new ContractStatus_Reserv () { dtFinishReserv = Convert.ToDateTime(t.Text) };
        }
    }

    private Contract Contract
    {
        get
        {
            wsContract ws = (wsContract)GlobalConstants.CurrentAgency.WS_FactoryList[WS_FactoryList.wsKey_Contract]; 
            Contract c= ws.GetContract(ContractID);
            c.BusinesRulesEngine.OnError= OnError;
            return c;
        }
     
    }

    protected bool OnError(List <string > Err)
    {
        string s = ScriptBuilder.GetAlertScript(Err);
        System.Web.UI.ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), s, true);
        return true;
    }
  
    protected List<grdContract> ContractAsList 
    {
        get 
        {
                
            List<grdContract> r = new List<grdContract>();
            r.Add(grdContract);
            return r;
        }
    }

    protected string ContractID { get { return Request.QueryString[qContractID]; } }

    protected grdContract grdContract
    {
        get { return new grdContract(Contract); }
    }
    

    #region ListView

    

    private bool lvClientEdit(ListViewDataItem EditItem)
    {

        Ctl_ctlClientListSelector c = (Ctl_ctlClientListSelector)EditItem.FindControl("ctlClientListSelector1");
        if (null == c)
            return true ;
        if (null != Contract.Client)
        {
            c.Client = Contract.Client;
            c.Where.ListLoadStatment.Lexeme = Contract.Client.Name.Replace(" ", "%");
        }
        return true;
    }


    protected  void ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (string.Empty == e.CommandName) return;
        ListView lv = (ListView)sender;        
        //Func<ListViewDataItem, bool> OnLvEditCommand=null;
        //if (lv.ID == "lvClient")
        //    OnLvEditCommand = lvClientEdit;


        switch (e.CommandName)
        {
            case "Edit":
                {
                    ListViewDataItem d = (ListViewDataItem)e.Item;
                    lv.EditIndex = d.DataItemIndex;                    
                    break;
                }
            case "Insert":
                {
                    break;
                }
            case "Update":
                {                    
                    lv.EditIndex = -1;
                    SetMsg_EditStatus ();
                    break;
                }
            case "Delete":
                {
                    
                    break;
                }
        }

        switch (lv.ID)
        {

            //case "lvSurfaceSet":
            //    lvSurfaceSet.DataSource  = ContractAsList;
            //    lvSurfaceSet.DataBind();                
            //    break;
            default:
                lv.DataSource = ContractAsList;
                break;
        }
        lv.DataBind();
        
        SetAlertForTextBox(this.Controls, "TextBox", "onChange", "ShowAlert()");
        SetMsg_EditStatus();        
    }

    protected  void ItemUpdating(object sender, ListViewUpdateEventArgs e)
    {

    }    
    
    protected void lvClient_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        //Ctl_ctlClietEditorl c = (Ctl_ctlClietEditorl)e.Item.FindControl("ctlClientEditor1");
        //if (null == c) return;
        //c.PageSize = 7;
        //c.OnSelectedClick = ctlClietEditorl_OnSelectedClick;
        //if (Contract.Client != null) c.Lexeme = Contract.Client.Name;
        //c.DataBind();
    }


    protected void lvSurfaceSet_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        //if (lvSurfaceSet.EditIndex == -1)
        //{
        //    Ctl_ctlSurfaceListBrowser ct = (Ctl_ctlSurfaceListBrowser)e.Item.FindControl("ctlSurfaceListBrowser1");
        //    ct.ContractSupplier = ctlSurfaceListBrowser_ContracttSupplier; 
        //    ct.DataBind();

        //}
    }


    protected void ItemEditing(object sender, ListViewEditEventArgs e)
    {

        ListView lv = (ListView)sender;
        switch (lv.ID)
        {
            case "lvClient":
                {
                    Ctl_ctlClientListSelector c = (Ctl_ctlClientListSelector)lvClient.EditItem.FindControl("ctlClientListSelector1");
                    if (null == c)
                                return;
                    
                    if (null != Contract.Client)
                    {
                        c.Client = Contract.Client;
                        c.Where.ListLoadStatment.Lexeme = Contract.Client.Name.Replace(" ", "%");
                        c.MyDataBind();

                    }

                    break;
                }

        }
        //if (lblClientStatus.ID == "ListView" && lv.EditItem != null)
        //{
        //    //Ctl_ctlSurfaceList ct = (Ctl_ctlSurfaceList)lvSurfaceListFrame.EditItem.FindControl("ctlSurfaceList");
        //    //ct.StartPeriod = grdContract.StartDate;
        //    //ct.EndPeriod = grdContract.EndDate;

        //}
    }

    #endregion

    /// <summary>
    /// Вернуть описательный заголовок контракта
    /// </summary>
    /// <returns></returns>
    protected string GetContractCaption()
    {
        string[] s = { "", "" };
        switch (grdContract.Contract.ContractStatus.ID)
        {
            case GlobalConstants.Contract_Contract:
                return "Контракт № " + grdContract.Contract.Number + " | " + grdContract.Contract.Client.Name;

            case GlobalConstants.Contract_Advice:
                return "Контракт № " + grdContract.Contract.Number;

            case GlobalConstants.Contract_Reserv:
                return "Контракт № " + grdContract.Contract.Number + " | " + grdContract.Contract.Client.Name + " | " + ((ContractStatus_Reserv)grdContract.Contract.ContractStatus).dtFinishReserv.ToShortDateString();

        }
        return string.Empty;
    }

    protected string GetdtFinishReserv()
    {
        if (Contract.ContractStatus is ContractStatus_Reserv)
        {
            return ((ContractStatus_Reserv)Contract.ContractStatus).dtFinishReserv.ToShortDateString();
        }
        return string.Empty;
    }

    protected Contract ctlSurfaceListBrowser_ContracttSupplier()
    {
        return Contract;
    }


    #region Clic    k

    private bool ctlClietEditorl_OnSelectedClick(Client Client)
    {
        grdContract.Contract.Client = Client;               
        lvClient.EditIndex = -1;
        MyDataBind();
        return true;

    }
    
    protected void btnSaveCommonInfo_Click(object sender, EventArgs e)
    {
        ReadForm();

        if (Check())
            SaveContract();

        MyDataBind();

    }

    private bool Check()
    {   
        return Contract.BusinesRulesEngine.Check ();
     
    }
        
    protected void ReturnToList(object sender, EventArgs e)
    {
        string s = "PageProcessor.aspx?Page=iSales_ContractList.aspx";
        Response.Redirect(s);
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
         
        ContractSurfaceItem item = new ContractSurfaceItem (){ID="07393582-010a-4e91-aff3-8235002d445b"};
        //Contract.SurfaceList.Add   (item);
    }

    
 
    protected void Button5_Click(object sender, EventArgs e)
    {
        
       


    }
 
    /// <summary>
    /// Cформировать график платежей.
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnGrafik_Click(object sender, EventArgs e)
    {
        Contract.ContractStatus = new ContractStatus_Contract();
        MyDataBind();
    }

   

    

    protected string GetCancelControlID_PaymentsPlan()    
    {
        return "";
    }

    #endregion

    protected bool IsContract
    {
        get { return Contract.ContractStatus.ID == GlobalConstants.Contract_Contract; }
    }


    protected void btnCloseSurfaceListEdit_OnClick(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        popPaymentPlan_ModalPopupExtender.Hide();
    }
    protected void ShowPaymentGrafik_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        popPaymentPlan_ModalPopupExtender.Show();
    }

    protected Unit PnlSurfSetEditWidtch 
    { 
            get{return  new Unit (GlobalConstants.ScreenValues.W-100);}   
    }

    protected void BtnShedule_OnClick(object sender, EventArgs e)
    {
        Response.Redirect("iSales_Shedule.aspx?ContractId="+Contract .ID);
    }

    protected Unit PnlSurfSetEditHight
    {
        get { return new Unit(GlobalConstants.ScreenValues.H ); }
    }
    protected void btnGridMode_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        MultiView1.ActiveViewIndex = (MultiView1.ActiveViewIndex == 0 ? 1 : 0);
        if (MultiView1.ActiveViewIndex == 1)// Инициализируем SideShedule
        {
            if (Contract.ContractSurfaceItemList.Count == 0)
            {
                ctlSideShedule1.DtStart = DateTimeTools.GetFisrtDayInMonth(DateTime.Now);
                ctlSideShedule1.DtEnd = DateTimeTools.GetFisrtDayInMonth(DateTime.Now).AddMonths (1); 
            }
            else
            {
                ctlSideShedule1.DtStart = grdContract.StartDate;
                ctlSideShedule1.DtEnd = grdContract.EndDate;
            }
            ctlSideShedule1.Contract = Contract;
            ctlSideShedule1.DetailsPeriod = DateTimeTools.TimePeriod.Month;
            ctlSideShedule1.EnabeBind = true;
            ctlSideShedule1.Q_TypeSet = new SideListWithContracts.SqlLoadStatment.Q_Type[] { SideListWithContracts.SqlLoadStatment.Q_Type.OnlySelected };
            ctlSideShedule1.DataBind();
            
        
        }
        else //ctlSurfaceListBrowser1
        {
            ctlSurfaceListBrowser1.ContractSupplier = ctlSurfaceListBrowser_ContracttSupplier;
            ctlSurfaceListBrowser1.DataBind();


        }
        
    }
    protected void lvMode_ItemEditing(object sender, ListViewEditEventArgs e)
    {
        //if (lvMode.EditIndex == -1)
        //                        return;        
        //Ctl_ctlSideShedule c = (Ctl_ctlSideShedule)lvMode.EditItem.FindControl("ctlSideShedule1");
        //c.Contract = Contract;
        //c.DtStart = grdContract .StartDate ;
        //c.DtEnd = grdContract.EndDate ;
        //c.DetailsPeriod = DateTimeTools.TimePeriod.Month;
        //c.EnabeBind = true;
        //c.DataBind();
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        object j = e;
    }
}
